<template>
  <el-container class="bigbox">
    <el-header>
      <img src="../../image/study.jpg" alt="logo">
      <span>微服务卷B</span>
    </el-header>
    <el-container>
      <!-- 左侧 -->
      <el-aside style="position: relative;" class="left-sidebar"></el-aside>
      <!-- 右侧 -->
      <el-main>
        <div class="form-box">
          <div class="signup-div">
            <span :class="{ 'bottom': bottom.active }" id="signup_btn" @click="signupBtn">登录</span>
            <span class="line">|</span>
            <span :class="{ 'bottom': !bottom.active }" id="signdown_btn" @click="signdownBtn">注册</span>
          </div>
          <el-form v-if="signupOrSigndown" ref="loginRefForm" :model="user" label-width="100px" :rules="loginRules">
            <el-form-item label="账号" prop="username">
              <el-input v-model="user.username" placeholder="4到16位(字母,数字,下划线,减号)" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input type="password" v-model="user.password" placeholder="6到18位数字" />
            </el-form-item>
            <el-form-item>
              <el-button class="signup-btn" type="primary" @click="login">登 录</el-button>
            </el-form-item>
          </el-form>
          <el-form v-else ref="loginRefForm" :model="userSignIn" class="signUp" label-width="100px" :rules="signInRules">
            <el-form-item label="用名：" prop="username">
              <el-input v-model="userSignIn.username" placeholder="4到16位(字母,数字,下划线,减号)" />
            </el-form-item>
            <el-form-item label="密码：" prop="password">
              <el-input v-model="userSignIn.password" type="password" placeholder="6到18位数字" />
            </el-form-item>
            <el-form-item label="确认密码：" prop="passwordAgain">
              <el-input v-model="userSignIn.passwordAgain" type="password" placeholder="请再次输入密码" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="signDownBtn" @click="signIn">注册</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive } from 'vue'
import { doGet, doPost } from "../../http/httpUserRequest.js";
import { getTokenName, messageTip, removeToken } from "../../util/util.js";
// 定义页面使用到的变量，定义时初始值都是给个空的
let signupOrSigndown = ref(true);
let bottom = reactive({ active: true });
let user = reactive({});
let userSignIn = reactive({ username: '', password: '', passwordAgain: '' });
let name = ref('');
// 定义登录表单的验证规则
let loginRules = {
  username: [
    { required: true, message: '请输入登录账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入登录密码', trigger: 'blur' },
    { min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur' }
  ],
};
// 定义注册表单的验证规则
let signInRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 16, message: '用户名长度应在4到16个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '密码长度应在6到18个字符之间', trigger: 'blur' }
  ],
  passwordAgain: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: checkPasswordAgain, trigger: 'blur' }
  ],
};
// 注册密码验证两次输入是否一样
function checkPasswordAgain(rule, value, callback) {
  if (value !== userSignIn.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}
// 切换注册登录按钮
function signupBtn() {
  bottom.active = true;
  signupOrSigndown = true;
}
function signdownBtn() {
  bottom.active = false;
  signupOrSigndown = false;
}
// 注册函数
function signIn() {
  // 提交前验证输入框的合法性
  if (!instance) return;
  instance.refs.loginRefForm.validate((isValid) => {
    // isValid是验证后的结果，如果是true表示验证通过，否则未通过
    if (isValid) {
      // 验证通过，可以提交注册
      let formData = new FormData();
      formData.append("username", userSignIn.username);
      formData.append("password", userSignIn.password);
      doPost("/user/signIn", formData).then((resp) => {
        if (resp.data.code === 200) {
          // 登录成功，提示一下
          messageTip("登录成功", "success");
          // 删除一下历史localStorage和sessionStorage中存储的token
          removeToken();
          // 跳转到登录页面
          window.location.href = "/";
        } else {
          // 登录失败，也提示一下
          messageTip("登录失败", "error");
        }
      });
    }
  });
}
// 登录函数
function login() {
  // 提交前验证输入框的合法性
  if (!instance) return;
  instance.refs.loginRefForm.validate((isValid) => {
    // isValid是验证后的结果，如果是true表示验证通过，否则未通过
    if (isValid) {
      // 验证通过，可以提交登录
      let formData = new FormData();
      formData.append("loginAct", user.loginAct);
      formData.append("loginPwd", user.loginPwd);
      formData.append("captcha", user.captcha);
      formData.append("rememberMe", user.rememberMe);
      doPost("/user/login", formData).then((resp) => {
        if (resp.data.code === 200) {
          // 登录成功，提示一下
          messageTip("登录成功", "success");
          // 删除一下历史localStorage和sessionStorage中存储的token
          removeToken();
          // 前端存储jwt
          if (user.rememberMe === true) {
            window.localStorage.setItem(getTokenName(), resp.data.data);
          } else {
            window.sessionStorage.setItem(getTokenName(), resp.data.data);
          }
          // 跳转到系统的主页面
          window.location.href = "/dashboard";
        } else {
          // 登录失败，也提示一下
          messageTip("登录失败", "error");
        }
      });
    }
  });
}
// 免登录（自动登录）
function freeLogin() {
  let token = window.localStorage.getItem(getTokenName());
  if (token) { // 表示token有值，token不是空，token存在
    doGet("/user/login/free", {}).then(resp => {
      if (resp.data.code === 200) {
        // token验证通过了，那么可以免登录
        window.location.href = "/dashboard";
      }
    });
  }
}
</script>

<style scoped>
.bigbox {
  height: calc(98vh - 88px); /* 修改高度 */
  width: 100%;
}
.form-box {
  border: 1px solid #ccc;
  box-shadow: 0 0 10px 1px #ccc;
  border-radius: 8px;
  width: 441px;
  height: 303px;
  margin: auto;
  margin-top: 50px; /* 修改上边距 */
}
.signup-div {
  margin-bottom: 30px;
  margin-top: 30px;
  margin-left: 50px;
}
.signup-div .line {
  font-size: 20px;
}
.signup-div .signdown-btn, .signup-div .signup-btn {
  font-size: 25px;
  font-weight: bold;
  cursor: pointer;
}
.signup-div .signdown-btn:hover, .signup-div .signup-btn:hover {
  color: #393939;
}
.bottom {
  border-bottom: 6px solid skyblue;
}
.left-sidebar {
  background: #1a1a1a; /* 修改背景颜色 */
  width: 50%; /* 修改宽度 */
  background-image: url(../../image/SignUp.jpg); /* 修改背景图片 */
  background-repeat: no-repeat;
  background-size: cover; /* 修改背景大小 */
}
.el-main {
  height: 100%; /* 修改高度 */
}
.imgTitle {
  color: #f9f9f9; /* 修改文字颜色 */
  font-size: 28px; /* 修改字体大小 */
}
.loginTile {
  text-align: center;
  margin-top: 100px; /* 修改上边距 */
  margin-bottom: 25px; /* 修改下边距 */
  font-weight: bold;
}
.el-header {
  width: 100%;
  height: 8%; /* 修改高度 */
  background-color: #393939; /* 修改背景颜色 */
  position: relative;
}
.el-header span {
  font-weight: bold;
  font-size: 30px; /* 修改字体大小 */
  font-style: italic; /* 修改字体样式 */
  vertical-align: top; /* 修改垂直对齐方式 */
  line-height: 250%; /* 修改行高 */
}
.el-header img {
  width: 4%; /* 修改宽度 */
  height: 100%; /* 修改高度 */
  margin-left: 2%; /* 修改左边距 */
}
</style>
```